<?php

namespace app\common;

use app\common\enum\Code;
use think\exception\HttpResponseException;
use think\facade\Log;
use think\response\Json;

class Result
{

    public static function success(mixed $data = null, int $code = Code::Success->value): Json
    {
        return self::result($code, '', $data);
    }

    public static function fail(string $msg = Code::Fail->name, int $code = Code::Fail->value): Json
    {
        return self::result($code, $msg);
    }

    public static function failByCode(Code $code): Json
    {
        return self::fail($code->value, $code->msg());
    }

    public static function httpException(string $msg, int $code = Code::Fail->value)
    {
        throw new HttpResponseException(self::fail($msg, $code));
    }

    public static function dbException(array $dbMsg, int $code = Code::Fail->value)
    {
        if (isset($dbMsg['Database Status'])) {
            Log::error(json_encode($dbMsg['Database Status']));
        }

        $msg = $dbMsg['Database Status']['Error Message'];
        if (str_contains($msg, 'too long')) {
            $msg = '字段数据太长';
        }

        throw new HttpResponseException(self::fail($msg, $code));
    }

    public static function httpExceptionByCode(Code $code): Json
    {
        return self::httpException($code->msg(), $code->value);
    }

    public static function result(int $code, string $msg = '', mixed $data = null): Json
    {
        return json(compact('code', 'data', 'msg'));
    }
}